var Robot = require("./Robot");
var schedule = require("node-schedule");
var stockChannelDAO = require("../controller/controller.stockChannel");
var stockDealDAO = require("../controller/controller.stockDeal");
var stockGroupDAO = require("../controller/controller.stockGroup");
var stockGroupRateDAO = require("../controller/controller.stockGroupRate");
var stockHistoryPriceDAO = require("../controller/controller.stockHistoryPrice");
var stockUtil = require('../utils/stock');
var stockGroupUtil = require('../utils/stockGroup');

var async = require('async');

exports.saveStockGroupRate = function () {
    function getTime2Time($time1, $time2) {
        var time1 = arguments[0], time2 = arguments[1];
        time1 = Date.parse(time1) / 1000;
        time2 = Date.parse(time2) / 1000;
        var time_ = time1 - time2;
        return (time_ / (3600 * 24));
    }

    // function getAfterFiveDay(day, dayLen) {
    //     var days = [];
    //     var d = new Date(day.replace(/-/g, "/"));
    //     var i = dayLen < 5 ?1:dayLen / 5 ;//当前日期加i天,小于5天算一天
    //     var count = i == 1?i:5;
    //     for (var j = 0; j < count; j++) {
    //         d.setDate(d.getDate() + i);
    //         days.push(formatDate(d));
    //     }
    //     return (days);
    // }
    //
    // function formatDate(date,type,num) {
    //     if(num)return null;
    //     if(type == 'year')
    //         return (date.getFullYear()+num) + "-" + (date.getMonth() + 1) + "-" + (date.getDate())
    //     if(type == 'month' )
    //         return (date.getFullYear()) + "-" + (date.getMonth() + 1+num) + "-" + (date.getDate())
    //     if(type == 'day' )
    //         return (date.getFullYear()) + "-" + (date.getMonth() + 1) + "-" + (date.getDate()+num)
    // }
    // function formatYesterDayDate(date) {
    //     return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate()-1)
    // }
    // function countRate(result, stockGroup) {
    //     let oldPrice = 0;
    //     let realPrices = 0;
    //     if (result.length == 0 || result.startDeals.length == 0) {//开始前未买入
    //         if (result.length == 0 || result.endDeals.length == 0) {//开始后未买入
    //             return '0%';
    //         } else {//开始后买入
    //             for (item of result.endDeals) {
    //                 oldPrice += item.val;
    //             }
    //             for (stockChannel of stockGroup.stockChannelIds) {
    //                 realPrices += stockChannel.positionNum * stockChannel.stockId.realPrice;//现价*总量
    //             }
    //             return (stockUtil.calcRate(realPrices, oldPrice));
    //         }
    //     } else {//开始前买入
    //         for (stockChannel of stockGroup.stockChannelIds) {
    //             //if( result.endDeals.length > 0){
    //             // var inStartDeals = 0;
    //             for (item of result.endDeals) {
    //                 if (stockChannel.stockId.stockCode.substring(0, stockChannel.stockId.stockCode.indexOf(".")) == item.stockCode) {
    //                     for (stockPrice of result.firstPrice) {
    //                         if (stockChannel.stockId.stockCode.substring(0, stockChannel.stockId.stockCode.indexOf(".")) == stockPrice.stockCode) {
    //                             //oldPrice += stockPrice.price * ((stockChannel.positionNum - item.nums)==0?item.nums:(stockChannel.positionNum - item.nums));
    //                             oldPrice += item.val;
    //
    //                         }
    //                     }
    //                 }
    //             }
    //             realPrices += stockChannel.positionNum * stockChannel.stockId.realPrice;//现价*总量
    //             for (item of result.startDeals) {
    //                 //inStartDeals++;
    //                 if (item.stockCode == stockChannel.stockId.stockCode.substring(0, stockChannel.stockId.stockCode.indexOf("."))) {
    //                     for (stockPrice of result.firstPrice) {
    //                         if (item.stockCode == stockPrice.stockCode) {
    //
    //                             oldPrice += stockPrice.price * item.nums;
    //
    //                         }
    //                     }
    //                 }
    //             }
    //         }
    //         return (stockUtil.calcRate(realPrices, oldPrice));
    //     }
    // }

    function save() {
        var params = {};
        async.waterfall([
            function (done) {//删除所有统计
                stockGroupRateDAO.delete(params, function (err, result) {
                    if (err) {
                        done({'code': 404, 'message': "清空分组错误"});
                        return;
                    }
                    done(err, result.obj);
                });
            },
            function (res,done) {//查询所有分组
                stockGroupDAO.list(params, function (err, result) {
                    if (err) {
                        done({'code': 404, 'message': "查询分组错误"});
                        return;
                    }
                    var list = [];
                    if (result && result.obj) {
                        list = result.obj;
                    }
                    done(err, list);
                });
            },
            function (stockGroups, done) {//按股票查询实价
                async.each(stockGroups, function (stockGroup, callback) {
                    var stockCodes = [];
                    stockChannelDAO.getByGroupId({stockGroupId: stockGroup.rowId}, function (err, res) {
                        stockGroup.stockChannelIds = res.obj;
                        for (stockChannel of res.obj) {
                            stockCodes.push(stockChannel.stockId.stockCode);

                        }
                        if (stockCodes.length == 0) {
                            callback();
                        } else {
                            stockUtil.getRealtimeListPrice(stockCodes, function (err, res) {
                                var i = 0;
                                for (stockChannel of stockGroup.stockChannelIds) {
                                    stockChannel.stockId.realPrice = res[i];
                                    i++;
                                }
                                callback();
                            });
                        }
                    });

                }, function (err) {
                    done(err, stockGroups);
                });
            },
            function (stockGroups, done) {//按股票查询各区间价格做收益率统计
                async.each(stockGroups, function (stockGroup, call) {
                    // if (stockGroup.stockGroupRates.length > 0) {//组合收益已存在记录,获取存在的最大时间 向后继续加入新数据
                    var stockGroupRate = {};
                    stockGroupUtil.countGroupRate(stockGroup, function (err, res) {
                            async.each(res, function (firstDay, callback) {
                                stockGroupRate.rate = firstDay.realRate;
                                stockGroupRate.stockGroupId = stockGroup.rowId;
                                stockGroupRate.positionRate = '80';
                                stockGroupRate.countDate = firstDay.day;
                                //保存
                                stockGroupRateDAO.create(stockGroupRate, function (err, res) {
                                    callback(null, res)
                                })
                            });
                        }, function (err) {//五天数据循环出
                            done(err, res);
                        }
                    );

                })
            }
        ], function (error, result) {
            if (error) {
                console.log(error);

            } else {
                console.log("更新收益率结束")
            }
        });


    }

    var rule = new schedule.RecurrenceRule();

    rule.dayOfWeek = [0, new schedule.Range(1, 6)];

    rule.hour = 08;

    rule.minute = 06;

    console.log("定时爬取任务，下次爬取时间为" + rule.hour + "时" + rule.minute + "分");

 var j = schedule.scheduleJob(rule,function(){

    // robot.setOpt({
    //     outputFileName: getTime() + "-" + "stock.txt"
    // });
    // console.log("开始定时爬取任务...");
    save();
 });

}


// robot end